import { Controller, Post, Body, ConflictException, Logger, Session } from '@nestjs/common';
import { AuthService } from './auth.service';
import { RegisterDto } from './dto/register.dto';
import { LoginDto } from './dto/login.dto';
import { ApiTags, ApiOperation, ApiBody } from '@nestjs/swagger';
import { CaptchaService } from './captcha.service';
import { UsersService } from '@modules/users/users.service';

@ApiTags('Auth')
@Controller('auth')
export class AuthController {
  // private readonly logger = new Logger(AuthController.name); // 添加 Logger
  constructor(
    private authService: AuthService,
    private readonly captchaService: CaptchaService,
    private readonly userService: UsersService,
  ) { }

  @Post('register') // 完整路由为 /auth/register
  async register(@Body() registerDto: RegisterDto) {
    return this.authService.register(registerDto);
  }

  @Post('login')
  @ApiOperation({ summary: '用户登录' })
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        username: { type: 'string', example: 'admin' },
        password: { type: 'string', example: '123456' },
        captcha: { type: 'string', example: '1a2b' },
      },
      required: ['username', 'password', 'captcha'],
    },
  })
  async login(@Body() loginDto: LoginDto, @Session() session) {
    // 校验验证码
    const sessionId = session.id;
    const captchaValid = this.captchaService.validateCaptcha(
      sessionId,
      loginDto.captcha,
    );

    if (!captchaValid) {
      return { success: false, message: '验证码错误或已过期', code: 400 };
    }

    // 从数据库验证用户名和密码
    const user = await this.userService.validateUser(
      loginDto.username,
      loginDto.password
    );

    if (!user) {
      return { success: false, message: '用户名或密码错误', code: 401 };
    }

    return {
      success: true,
      message: '登录成功',
      code: 200,
      data: { userId: user.id, username: user.username }
    };
  }
} 